package com.juku2024.juku.widget

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.rabbit.videoplayer.OnVideoStatusListener
import com.rabbit.videoplayer.listener.OnEpisodeClickCallback
import com.rabbit.videoplayer.tools.Constants
import com.juku2024.juku.R
import com.juku2024.juku.adapter.VideoDetailEpisodeAdapter
import com.juku2024.juku.model.EpisodesResponse
import com.juku2024.juku.tools.RxUtils
import com.juku2024.juku.tools.WrapGridLayoutManager
import com.juku2024.juku.tools.WrapLinearLayoutManager
import io.reactivex.disposables.Disposable

class ControlEpisodeListView(context: Context, attrs: AttributeSet? = null): ConstraintLayout(context, attrs), OnVideoStatusListener {

    private var isShowingView = false
    private var episodeClick: OnEpisodeClickCallback? = null
    private val episodeListAdapter by lazy { VideoDetailEpisodeAdapter(ArrayList()) }

    private val episodeRecycler: RecyclerView
    init {
        val rootView = LayoutInflater.from(context).inflate(R.layout.diglog_control_episode_list, this, true)
        rootView.setBackgroundColor(Color.parseColor("#80000000"))
        rootView.visibility = View.GONE
        rootView.isClickable = true
        rootView.isFocusable = true

        val hideView = rootView.findViewById<View>(R.id.toucheHideView)
        hideView.setOnClickListener {
            hide()
        }

        episodeRecycler = rootView.findViewById(R.id.recyclerEpisode)
        episodeRecycler.addOnScrollListener(object: OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    if (showDisposable != null && !showDisposable!!.isDisposed) {
                        showDisposable!!.dispose()
                    }
                } else {
                    // 自动隐藏
                    showDisposable?.dispose()
                    showDisposable = RxUtils.delay(3000) {
                        hide()
                    }
                }
            }
        })
        episodeListAdapter.setOnItemClickListener { _, _, position ->
            // 获取当前正在播放的剧集的position
            val currentPlayingPosition = episodeListAdapter.data.indexOfFirst { it.isPlaying }
            // 屏蔽重复点击正在播放的节目
            if (currentPlayingPosition == position) return@setOnItemClickListener
            // 修改剧集列表ui
            val currentItem = episodeListAdapter.getItem(currentPlayingPosition)
            currentItem.isPlaying = false
            episodeListAdapter.notifyItemChanged(currentPlayingPosition)
            // 切换到指定的剧集
            episodeListAdapter.getItem(position).isPlaying = true
            episodeListAdapter.notifyItemChanged(position)

            val realPos = if (isEpisodeReverse) {
                episodeListAdapter.data.size - position - 1
            } else {
                position
            }

            episodeClick?.onEpisodeClick(position, realPos)

            hide()
        }
        hide()
    }


    fun setEpisodeClickCallback(episodeClick: OnEpisodeClickCallback?) {
        this.episodeClick = episodeClick
    }

    private var showDisposable: Disposable? = null
    fun show() {
        isShowingView = true
//        val animator: ObjectAnimator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f)
//        animator.duration = 200
//        animator.interpolator = DecelerateInterpolator()
//        animator.start()
        visibility = View.VISIBLE
        // 自动隐藏
        showDisposable = RxUtils.delay(2700) {
            hide()
        }
    }


    fun hide() {
        showDisposable?.dispose()
        isShowingView = false
        visibility = View.GONE
//        val animator: ObjectAnimator = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f)
//        animator.duration = 200
//        animator.interpolator = AccelerateInterpolator()
//        animator.start()
    }



    fun isShowing(): Boolean {
        return isShowingView
    }

    override fun onVodInit(vararg init: Any?): Boolean {
        if (init.isEmpty()) return false
        val paramsList = init[0] as ArrayList<*>
        val episodeList = ArrayList<EpisodesResponse>()
        paramsList.forEach {
            if (it is EpisodesResponse) {
                episodeList.add(it)
            }
        }
        if (episodeList.isEmpty()) {
            return true
        }
        episodeListAdapter.category = episodeList.first().category
        val layoutManager = if (episodeListAdapter.category == Constants.VIDEO_CATEGORY_ALBUM) {
            WrapGridLayoutManager(context, 5)
        } else {
            WrapLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        }
        episodeRecycler.layoutManager = layoutManager
        episodeRecycler.adapter = episodeListAdapter
        episodeListAdapter.setList(episodeList)
        val index = episodeListAdapter.data.indexOfFirst { it.isPlaying }
        if (index < layoutManager.findFirstVisibleItemPosition() || index > layoutManager.findLastVisibleItemPosition()) {
            episodeRecycler.post {
                episodeRecycler.scrollToPosition(index)
            }
        }

        return false
    }

    override fun onVodPrepared(vararg prepared: Any) {
        
    }

    override fun onVodStart() {
        
    }

    override fun onVodFirstFrameStart() {
        
    }

    override fun onVodSwitchDisplayControlView() {
        
    }

    override fun onVodPause() {
        
    }

    override fun onVodStop() {
        if (isShowing()) {
            showDisposable?.dispose()
            hide()
        }
    }

    override fun onVodError(vararg params: Any) {
        if (isShowing()) {
            showDisposable?.dispose()
            hide()
        }
    }

    override fun onVodComplete() {

    }

    override fun onVodRelease() {

    }

    override fun onVodLockedScreen(vararg params: Any) {
        
    }

    override fun onVodFullScreen(vararg params: Any) {
        
    }

    override fun onVodLoadingBegin() {
        
    }

    override fun onVodLoadingProgress(vararg params: Any) {
        
    }

    override fun onVodLoadingEnd() {
        
    }
    override fun onVodBackPress(): Boolean {
        val isShowing = isShowing()
        if (isShowing()) {
            showDisposable?.dispose()
            hide()
        }
        return isShowing
    }

    override fun onEpisodeSelected() {
        if (isShowing()) {
            hide()
        } else {
            show()
        }
    }

    override fun onVodShowUnlockUI(isDisplayUI: Boolean) {
        if (isDisplayUI){
            if (isShowing()) {
                showDisposable?.dispose()
                hide()
            }
        }
    }
    // 当前剧集列表是否倒序
    private var isEpisodeReverse = false

    fun switchEpisodeOrder() {
        isEpisodeReverse = !isEpisodeReverse
        val liat = episodeListAdapter.data.asReversed()
        val target = ArrayList(liat)
        episodeListAdapter.setList(target)
        if (episodeRecycler.layoutManager == null) return
        val layoutManager = episodeRecycler.layoutManager as LinearLayoutManager
        val index = episodeListAdapter.data.indexOfFirst { it.isPlaying }
        if (index < layoutManager.findFirstVisibleItemPosition() || index > layoutManager.findLastVisibleItemPosition()) {
            episodeRecycler.post {
                episodeRecycler.scrollToPosition(index)
            }
        }
    }

}